package com.concandthreads;

import java.util.concurrent.Semaphore;

/**
 * Created by nkrivko on 08.12.2014.
 */
public class SemaphoreHolder {

    private final Semaphore semaphore = new Semaphore(6);
    private volatile int a;
    private volatile int b;

    public void doIt() {
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                try {
                    if (semaphore.hasQueuedThreads()) {
                        b++;
                    } else
                        a++;
                    semaphore.acquire();
                    Thread.currentThread().sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
                try {
                    semaphore.acquire();//re-acquire is permitted
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }
        };

        Runnable runnable3 = new Runnable() {
            @Override
            public void run() {
                System.out.println(a);
                System.out.println(b);
            }
        };
        new Thread(runnable1).start();
        new Thread(runnable1).start();
        new Thread(runnable1).start();
        new Thread(runnable1).start();
        new Thread(runnable3).start();
    }
}
